<template>
  <div class="el-page el-main el-position">
    <div class="search-box" id="search-box">
      <div class="search-card">
        <div class="input-box">
          <div class="searchCard">
            <span class="searchText">车牌号码：</span>
            <el-input class="shadowInput" v-model="form.carName" clearable size="mini" placeholder="请输入车牌号码"></el-input>
          </div>
          <div class="searchCard">
            <span class="searchText">作物类型：</span>
            <el-select class="shadowInput" size="mini" clearable v-model="form.cropType" placeholder="请选择作物类型">
              <el-option v-for="item in cropinfoList" :key="item.value" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </div>
          <div class="searchCard">
            <span class="searchText">仓号：</span>
            <el-select class="shadowInput" size="mini" clearable v-model="form.warehouseNumber" placeholder="请选择仓号">
              <el-option v-for="item, index in warehouseList" :key="item.value + index" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="searchCard">
            <span class="searchText">来自地块：</span>
            <el-select class="shadowInput" size="mini" clearable v-model="form.sourceTeam" placeholder="请选择生产队"
              @change="handleChangeMassifNumber">
              <el-option v-for="item, index in teamList" :key="item.value + index" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select class="shadowInput" size="mini" clearable v-model="form.massifNumber" placeholder="请选择地块">
              <el-option v-for="item, index in massifNumberList" :key="item.value + index" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="button-box">
          <el-button class="search" @click="getList">搜索</el-button>
          <el-button class="clear" @click="handleReset">清除</el-button>
        </div>
        <svg-icon class="svg-icon arrow" id="arrow" icon-class="rightArrow" @click="toggleDropdown" />
      </div>
      <div class="input-box">
        <div class="searchCard">
          <span class="searchText">作物品质：</span>
          <el-select class="shadowInput" size="mini" clearable v-model="form.cropQuality" placeholder="请选择作物品质">
            <el-option v-for="item, index in cropQualityList" :key="item + index" :label="item" :value="item">
            </el-option>
          </el-select>
        </div>
        <div class="searchCard">
          <span class="searchText">状态：</span>
          <el-select class="shadowInput" size="mini" clearable v-model="form.status" placeholder="请选择状态">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="searchCard">
          <span class="searchText">入库时间：</span>
          <el-date-picker v-model="timeList" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="mini" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
            @change="handleFormData">
          </el-date-picker>
        </div>
      </div>
    </div>
    <el-divider></el-divider>
    <div class="operate-box">
      <div class="button-box">
        <el-button v-if="hasIdentifier('Inbound.add')" class="addButton" type="primary" icon="el-icon-plus" size="mini"
          @click="handleShowAddDialog">新增</el-button>
        <el-popconfirm v-if="hasIdentifier('Inbound.delete')" style="margin:0 10px;" confirm-button-text='确定'
          cancel-button-text='取消' icon="el-icon-info" icon-color="red" title="确定删除所勾选的数据吗？" @confirm="handleDel">
          <el-button slot="reference" type="danger" plain icon="el-icon-delete" size="mini">删除</el-button>
        </el-popconfirm>
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleSelectAll">全选</el-button>
        <el-button v-if="hasIdentifier('Inbound.import')" type="warning" plain icon="el-icon-download" size="mini"
          @click="handleExport">导出</el-button>
        <el-button v-if="hasIdentifier('Inbound.order.apply')" type="success" plain icon="el-icon-tickets" size="mini"
          @click="handleApply">补单申请</el-button>
        <el-button v-if="hasIdentifier('Inbound.order.fill')" type="success" plain icon="el-icon-document-checked"
          size="mini" @click="handleReport">补单填报</el-button>
        <el-button v-if="hasIdentifier('Inbound.adds')" class="addButton" type="primary" icon="el-icon-plus" size="mini"
          @click="ClearChange">入库过磅</el-button>
      </div>
      <div>
        <span style="margin-right: 30px;">过磅净重（kg）：{{ nwTotal2 }}</span><br/>
        <span style="margin-right: 30px;">最终入库重（kg）：{{ nwTotal }}</span>
        
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button class="circleButtom" size="mini" icon="el-icon-refresh" circle @click="getList"></el-button>
        </el-tooltip>
      </div>
    </div>
    <div class="table-box">
      <TableCom ref="tableCom" :tableHead="tableHead" :tableData="tableData" :tableOperate="tableOperate"
        :showIndex="false" :delList.sync="delList">
      </TableCom>
    </div>
    <div class="page-box">
      <PageCom :page="pageData.current" :size="pageData.size" :total="total" @handleSize="handleSize"
        @handleCurrent="handleCurrent"></PageCom>
    </div>
    <!-- 新增弹框 -->
    <AddPopu ref="addPopu" :showDialog.sync="showAddDialog" @handleRefresh="getList" @handleUpdate="handleUpdate">
    </AddPopu>
    <!-- 查看 -->
    <ViewPopu ref="ViewPopu" :showDialog.sync="showViewDialog"></ViewPopu>
    <ClearBox ref="ClearBox" :showDialog.sync="showClearDialog" @handleRefresh="getList"
      @handlegetCarNumber="getCarNumber"></ClearBox>
    <!-- 补单申请 -->
    <ApplyPopu ref="ApplyPopu" :showDialog.sync="showApplyDialog"></ApplyPopu>
    <!-- 补单填报 -->
    <ReportPopu ref="ReportPopu" :showDialog.sync="showReportPopu" @handleAdd="handleShowAddDialog"
      @handleEdit="handleApply"></ReportPopu>
  </div>
</template>

<script>
import { tableApi, delApi, importApi, getWareNumberApi } from '@/api/inCage'
import { cropinfoSelectApi, selectApi } from '@/api/select'
import { getPlotUnitListApi } from '@/api/inStorage'
import { cropQualityApi } from '@/api/statisticalReport'
import { getCarLicense } from '@/api/table'
import { Message } from 'element-ui'
import { fileExport, filterSelect } from '@/utils/methods'
import TableCom from '@/components/TableCom'
import PageCom from '@/components/PageCom'
import AddPopu from './dialog/AddPopu.vue'
import ClearBox from './dialog/ClearBox.vue'
import ApplyPopu from '@/views/inStorage/dialog/ApplyDialog.vue'
import ReportPopu from '@/views/inStorage/dialog/ReportDialog.vue'
import ViewPopu from './dialog/ViewDialog.vue'
import { mapGetters } from 'vuex';
export default {
  components: {
    TableCom,
    PageCom,
    AddPopu,
    ClearBox,
    ApplyPopu,
    ReportPopu,
    ViewPopu
  },
  data() {
    return {
      form: {
        carName: '',
        cropType: '',
        warehouseNumber: '',
        cropQuality: '',
        status: '',
        startTime: '',
        endTime: '',
        sourceTeam: '',
        massifNumber: '',
      },
      pageData: {
        current: 1,
        size: 10
      },
      total: 0,
      nwTotal: 0,
      nwTotal2:0,
      tableHead: [{
        title: '流水号',
        prop: 'serialNumber'
      }, {
        title: '状态',
        prop: 'status'
      }, {
        title: '车牌号',
        prop: 'carName'
      }, {
        title: '仓号',
        prop: 'warehouseNumber'
      }, {
        title: '垛号',
        prop: 'stampId'
      }, {
        title: '种类',
        prop: 'cropType'
      }, {
        title: '品种',
        prop: 'cropVarieties'
      }, {
        title: '品质',
        prop: 'cropQuality'
      }, {
        title: '类别',
        prop: 'categoryName'
      }, {
        title: '过毛时间',
        prop: 'hairingTime'
      }, {
        title: '毛重(kg)',
        prop: 'gw'
      }, {
        title: '过皮时间',
        prop: 'peelingTime'
      }, {
        title: '皮重(kg)',
        prop: 'tare'
      }, {
        title: '净重(kg)',
        prop: 'nw'
      }, {
        title: '含水量(%)',
        prop: 'water'
      }, {
        title: '含油量(%)',
        prop: 'yau'
      }, {
        title: '面筋值(%)',
        prop: 'glutenValue'
      }, {
        title: '最终入库重(kg)',
        prop: 'solid'
      }, {
        title: '农场名称',
        prop: 'farmName'
      }, {
        title: '生产队名称',
        prop: 'sourceTeamName'
      }, {
        title: '填报时间',
        prop: 'createTime'
      }],
      tableData: [],
      tableOperate: [{
        title: '查看',
        handle: async (row) => {
          this.$refs.ViewPopu.getInfo(row.id)
          this.showViewDialog = true
        },
        flag: (row) => {
          return true
        }
      }, {
        title: '修改',
        handle: (row) => {
          // this.$refs.addPopu.handleGetSelect()
          this.$refs.addPopu.getInfo(row.id)
          this.showAddDialog = true
        },
        flag: (row) => {
          if (this.hasIdentifier("Inbound.update")) {
            // if (row.type == '2') {
            //   return false
            // } else {
              return true
            // }
          }

        }
      }],
      // 作物类型
      cropinfoList: [],
      // 状态
      statusList: [],
      // 作物品质
      cropQualityList: [],
      // 仓号
      warehouseList: [],
      // 生产队
      teamList: [],
      // 地块号
      massifNumberList: [],
      isDropdownVisible: false,
      timeList: [],
      showAddDialog: false,
      delList: [],
      showClearDialog: false,
      setTimeoutFun: null,
      showApplyDialog: false,
      showReportPopu: false,
      showViewDialog: false
    }
  },
  computed: {
    ...mapGetters(['hasIdentifier']), // 映射 getters
  },
  methods: {
    // 入场过磅
    ClearChange() {
      clearTimeout(this.setTimeoutFun)
      this.$refs.ClearBox.handleGetSelect()
      this.$refs.ClearBox.getZl()
      this.$refs.ClearBox.getCarNumber()
      this.showClearDialog = true
    },
    // 补单申请
    handleApply(row) {
      if (row.id) {
        this.$refs.ApplyPopu.ruleForm.orderWhy = row.orderWhy
        this.$refs.ApplyPopu.ruleForm.id = row.id
        this.$refs.ApplyPopu.ruleForm.status = '1'
      }
      this.$refs.ApplyPopu.ruleForm.orderType = '2'
      this.showApplyDialog = true
    },
    handleRefresh() {
      this.$refs.ReportPopu.getList()
    },
    // 补单填报
    handleReport() {
      this.$refs.ReportPopu.orderType = '2'
      this.$refs.ReportPopu.getList()
      this.showReportPopu = true
    },
    // 显示隐藏下拉框
    toggleDropdown() {
      const arrow = document.getElementById('arrow');
      const search = document.getElementById('search-box');
      if (!this.isDropdownVisible) {
        arrow.classList.add('down');
        search.classList.add('search-box-height');
      } else {
        arrow.classList.remove('down');
        search.classList.remove('search-box-height');
      }
      this.isDropdownVisible = !this.isDropdownVisible;
    },
    // 获取下拉框
    async handleGetSelect() {
      Promise.all([
        cropinfoSelectApi(),
        selectApi({ type: 'admission_status' }),
        cropQualityApi({ farmCode: this.$farmCode, teamCode: this.$teamCode }),
        getWareNumberApi({ farmCode: this.$farmCode, teamCode: this.$teamCode }),
        selectApi({ type: this.$farmCode }),
      ]).then(res => {
        this.cropinfoList = res[0].data
        this.statusList = res[1].data.dictItemList
        this.cropQualityList = res[2].data
        this.warehouseList = filterSelect(res[3].data)
        this.teamList = res[4].data.dictItemList
      })
    },
    // 地块
    async handleChangeMassifNumber() {
      this.form.massifNumber = ''
      this.massifNumberList = []
      let res = await getPlotUnitListApi({ teamId: this.form.sourceTeam })
      this.massifNumberList = res.data.map(item => {
        return {
          label: item.massifName,
          value: item.massifNumber
        }
      })
    },
    // 搜索框时间
    handleFormData() {
      if (this.timeList.length) {
        this.form.startTime = this.timeList[0]
        this.form.endTime = this.timeList[1]
      } else {
        this.form.startTime = ''
        this.form.endTime = ''
      }
    },
    // 全选取消全选
    handleSelectAll() {
      this.$refs.tableCom.toggleSelection(this.tableData)
    },
    // 重置
    handleReset() {
      this.form = {
        carName: '',
        carType: '',
        createUser: '',
        startTime: '',
        endTime: '',
      }
      this.timeList = []
    },
    // 获取表格
    async getList() {
      this.nwTotal = 0
      const { data } = await tableApi(this.form, this.pageData)
      this.total = data.list.total
      this.tableData = data.list.records;
      this.nwTotal =  data.total
      this.nwTotal2=data.total2
    },
    // 更新补单状态
    handleUpdate() {
      this.$refs.ReportPopu.handleUpdate()
    },
    // 分页
    handleSize(size) {
      this.pageData.current = 1
      this.pageData.size = size
      this.getList()
    },
    handleCurrent(current) {
      this.pageData.current = current
      this.getList()
    },
    handleShowAddDialog() {
      this.$refs.addPopu.handleGetSelect()
      this.$refs.addPopu.handleGetInfo()
      this.showAddDialog = true
    },
    // 删除
    async handleDel() {
      // 检查是否有 ID 在 idsArray 中并且状态为 'completed'
      const hasCompletedStatus = this.tableData.some(obj =>
        this.delList.includes(obj.id) && obj.status === '已完成'
      );
      if (hasCompletedStatus) {
        Message({
          message: '已完成状态下无法删除',
          type: 'error',
          duration: 2 * 1000
        })
      } else {
        let { code } = await delApi(this.delList)
        if (code == 0) {
          Message({
            message: '删除成功',
            type: 'success',
            duration: 3 * 1000
          })
        }
        this.getList()
      }
    },
    // 导出
    async handleExport() {
      let res = await importApi({ ...this.form, ids: this.delList })
      fileExport(res, '清选入库')
    },
    getCarNumber() {
      if (this.$status != 2) {
        return
      }
      this.setTimeoutFun = setTimeout(() => {
        if (this.showAddDialog) return
        getCarLicense({farmCode:this.$farmCode,teamCode:this.$teamCode?this.$teamCode:''}).then((res) => {
          // this.ruleForm.carName=res.data.data
          if (res.data.data !== '') {
            this.ClearChange()
          } else {
            this.getCarNumber()
          }
        })
      }, 2000)
    },
    getCarNumberRightAway() {
      if (this.$status != 2) {
        return
      }
      getCarLicense({farmCode:this.$farmCode,teamCode:this.$teamCode?this.$teamCode:''}).then((res) => {
        // this.ruleForm.carName=res.data.data
        if (res.data.data !== '') {
          this.ClearChange()
        } else {
          this.getCarNumber()
        }
      })
    },
  },
  mounted() {
    this.handleGetSelect()
    this.getList()
    this.getCarNumberRightAway()
  },
  beforeDestroy() {
    clearTimeout(this.setTimeoutFun)
    this.setTimeoutFun = null
  }
}
</script>

<style lang='scss' scoped>
.el-page {
  width: 100%;
  height: calc(100vh - 70px);

  .search-box {
    height: 40px;
    transition: height 0.3s ease;
    overflow: hidden;

    .search-card {
      width: 90%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;

      .arrow {
        cursor: pointer;
        display: inline-block;
        position: absolute;
        right: -100px;
        font-size: 30px;
        transition: transform 0.3s ease;
      }

      .arrow.down {
        transform: rotate(90deg);
      }
    }

    .input-box {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      transition: height 0.2s ease-in-out;
    }
  }

  .search-box-height {
    height: 90px;
  }

  .operate-box {
    width: 100%;
    background-color: #f5f7fa;
    padding: 8px 5px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

}
</style>
